import { mapState } from "vuex";
import { clearValue, clearKeys } from "@/utils/tool/object";
import getDate from "@/utils/tool/date";
import { deepCopy } from "@/utils/tool/object";
import { DynamicForm, contactsDynamicForm } from "@/components/DynamicForm";
import { DynamicCondition, FixedCondition } from "@/components/DynamicCondition";
import { DefineFieldList } from "@/api/crm/set";
import { UserFieldDetail, UserFieldSave } from "@/api/crm/userField";
import { initValidator, checkAll, checkNew } from "@/utils/validator/validator";
import { UserSearchDetail, UserSearchSave, UserSearchDelete } from "@/api/crm/userSearch";
import { IdFieldToNameField } from "@/utils/customize";

export default {
    props: {
        customerId: {
            type: Number,
            default: null
        },
        customer: {
            type: Object,
            default: () => ({})
        }
    },
    components: {
        FixedCondition,
        DynamicCondition,
        DynamicForm,
        contactsDynamicForm,//往来单位动态字段使用
    },
    data () {

        //表格 头部 可伸缩
        return {

            //----------↓样式----------
            btnGrid: {
                xs: 2,
                sm: 2,
                md: 2,
                lg: 2,
                xl: 2
            },
            //----------↑样式----------
            //gw 2021年8月28日09:14:35
            visibleSearchPlan: false,
            showDownPlan: false,//方案溢出显示
            iconDirection: true,//图标方向
            //gw 2021年8月28日09:14:35

            companyType: "isCustomer",    //往来单位 分类 （客户：isCustomer，供应商：isSupplier,其他：isOther）
            //   searchType: 5,        //0:线索客户 1.潜在客户 2.成交客户  3.联系人 4.联系人记录  5.商机
            //   source:"business",
            //   crmType: null,
            isNotTasking: false, //是否排除 外呼任务的 客户
            planActive: 0,//当前选择的查询方案id
            loading: false,                //列表数据加载
            basePostData: {},
            onOffDefineFields2Map: new Map(),
            onOffDefineFields4Map: new Map(),
            onOffDefineFields: [], //启用的自定义
            conditions: [], //启用 且 搜索的自定义
            fiexdColumnInTbCodes: [],                      //表头固定显示列Code(滑动漂浮)后期实现
            FixedConditionKeys: [],   //固定的搜索条件的Key
            FixedFormKeys: [],  //固定表单keys
            requiredCode: [],                            //必填的项
            excludeDefineFields: [],                       //排除的启用字段
            customRenderCode: [],                          //table 使用插槽的列
            RenderCodeChange: {},                          //table 插槽code转换
            customizeList: [], //当前source的所有自定义
            postData: {},
            isCollected: false,   //是否收藏
            initFormData: [], //动态表单自定义列数据
            initFormDataExclude: [],       //表单排除的code（特殊处理，不归到自动生成表单里面）
            formRules: {},    //动态表单 校验规则
            formPostData: {}, //动态表单 提交数据
            formErrors: {},   //表单验证错误信息
            isOk: true,
            isFromShow: true,
            numberReg: /^[1-9]{1}[0-9]*$/,
            floatReg: /^-?[0-9]*(\.[0-9]*)?$/,
            data: [],
            allColumns: [],
            columns: [],
            pagination: {
                size: "small",
                defaultPageSize: 20,
                current: 1,
                pageSize: 20,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input style="height:22px !important;width:3.2rem;"
                                value={this.pagination.pageSize}
                                min={1}
                                max={500}
                                size="small"
                                step={1}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                showQuickJumper: true,
                showLessItems: true
            },
            show: false, //是否显示
            editItem: {}, //新增/编辑对象
            ModalVisible: false,  //客户新增/编辑框 是否显示
            mySetVisible: false, //自定义列 是否显示
            mySetcheckedListLocal: [], //本地选择自定义列（未保存）
            mySetcheckedList: [], //本地选择自定义列 实际效果
            mySetplainOptions: [], //自定义列 数据源
            selectedKeys: [], //table选中的key
            selectedRows: [], //table选中的列
            userSearchList: [],            //常用查询条件集合(当前所有)
            userSearchEditItem: {},        //常用查询 编辑的Item
            userSearchSelectItem: {},      //常用查询 选中的Item
            userSearchSelect: "",          //常用查询选择的key
            UsRules: {
                "userSearchEditItem.searchName": { test: 'required' }
            },                            //常用查询 验证规则
            UsErrors: {},                 //常用查询 验证错误信息
            UsVisible: false,             //常用查询 编辑框是否显示
            blurEventMap: new Map(),       //失去焦点事件 Map
            isHistoryFlag: false,//是否是联系历史记录
        };
    },
    created () {
        const { isCollected, customerId, companyType } = this;
        let { crmType, isNotTasking } = this;
        if (customerId) {
            crmType = "";
        }
        this.GetCustomizeList();
        this.UserSearchDetail();
        this.basePostData = {
            isNotTasking,
            crmType,
            isCollected,
            companyType,
            customerIds: this.customerId,
            page: {
                current: 1,
                size: 20
            },
            dtos: []
        };
        this.postData = deepCopy(this.basePostData, true);
        console.log("创建时，this.postData", this.postData);
    },
    activated () {
        if (this.source) {
            this.PageList();
        }
    },
    mounted () {
        const { UsErrors, UsRules } = this;
        let vm = this;
        initValidator(vm, UsRules, UsErrors);
        console.log("常用查询 验证initValidator后", vm)


        /**
         * gw 处理方案过多溢出 2021年8月28日09:11:29
         */
        setTimeout(() => {
            //是否显示方案展开按钮
            this.showDownCheck();
        }, 500)
        window.onresize = () => {
            this.showDownCheck();
        }
    },
    computed: {
        errors: function () {
            return this.formErrors
        },
        myUsErrors: function () {
            return this.UsErrors
        },
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
            isCollectedState: state => state.order.isCollected,
        }),
    },
    methods: {

        //1...获取自定义字段配置
        GetCustomizeList () {

            let { source, customizeList, onOffDefineFields, conditions, excludeDefineFields } = this;
            const postData = {
                source
            };
            DefineFieldList(postData).then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    customizeList = data;
                    //排除 不参与的列
                    onOffDefineFields = customizeList.filter(f => f.onOff && !excludeDefineFields.includes(f.code));
                    console.log('来电反应，', onOffDefineFields)

                    let route = this.$route.path;
                    let routeArray = ['/crm/customer/list', '/crm/customer/potential', '/views/crm/customer/deals'];
                    if (routeArray.includes(route)) {
                        onOffDefineFields.push({
                            "name": "是否关注",
                            "code": "isCollected",
                            "source": "crm",
                            "type": "下拉",
                            "val": "是,否",
                            "length": "250",
                            "sort": 888,
                            "isSearch": true,
                            "onOff": true,
                            "dataType": 1,
                            "status": 1,
                            "columnWidth": 140,
                            "remarks": null,
                            "createUserId": 224,
                            "createUserName": "那都不是事儿",
                            "createDate": "2021-08-02 13:59",
                            "updateUserId": null,
                            "updateUserName": null,
                            "updateDate": "2021-08-02 13:59",
                            "dataIndex": 888
                        })
                    }

                    let routeArrayTouch = ['/crm/touch/list'];
                    if (routeArrayTouch.includes(route) && !this.customerId) {
                        // onOffDefineFields.push({
                        //     "name": "跟进方式",
                        //     "code": "type",
                        //     "source": "touch",
                        //     "type": "下拉选择",
                        //     "val": '[{"key":1,"title":"会话沟通"},{"key":2,"title":"外勤签到"}]',//1:会话沟通2:外勤签到
                        //     "length": "250",
                        //     "sort": 888,
                        //     "isSearch": true,
                        //     "onOff": true,
                        //     "dataType": 1,
                        //     "status": 1,
                        //     "columnWidth": 140,
                        //     "remarks": null,
                        //     "createUserId": 224,
                        //     "createUserName": "那都不是事儿",
                        //     "createDate": "2021-08-02 13:59",
                        //     "updateUserId": null,
                        //     "updateUserName": null,
                        //     "updateDate": "2021-08-02 13:59",
                        //     "dataIndex": 999
                        // })
                    }


                    conditions = onOffDefineFields.filter(f => f.isSearch );
                    console.log('conditions', conditions)
                    Object.assign(this, {
                        customizeList,
                        onOffDefineFields,
                        conditions
                    });
                    //初始化 自定义列 数据
                    this.initMySetplainOptions(onOffDefineFields);

                    //获取用户自定义表头，并更新表头
                    this.getUserFieldDetail();
                    console.log("获取自定义字段配置_pagelist")
                    this.planActive = 0;
                    //获取列表
                    this.PageList();
                }
            }).catch(error => { });
        },
        //2.初始化 自定义列 数据源
        initMySetplainOptions (onOffDefineFields) {
            const {
                formRules,
                formErrors,
                isAutomaticrelease,     //是否自动释放
                requiredCode,
                initFormDataExclude,
                FixedFormKeys,
            } = this;

            let initFormData = [];
            let mySetplainOptions = [];
            let mySetcheckedListLocal = [];
            //默认必填项
            requiredCode.forEach(code => {
                formRules["formPostData." + code] = { test: "required" };
            })

            onOffDefineFields.forEach(f => {
                let code = f.code;
                if (f.dataType == 3 || f.dataType == 4) {
                    code = f.parentCode;
                } else if (f.onEdit) {
                    //初始化 动态form表单 自定义列
                    if (!initFormDataExclude.includes(f.code) && !FixedFormKeys.includes(code)) {
                        initFormData.push({ ...f });
                    }
                    if (f.onFill) {
                        //初始化 校验对象和规则
                        formRules["formPostData." + f.code] = { test: "required" };
                    }
                    if ("email" == code) {
                        formRules["formPostData." + f.code] = { test: "email" };
                    }
                    if (isAutomaticrelease) {
                        formRules["formPostData.isRelease"] = { test: "required" };
                    }
                }
                //没有 被锁定的 可以编辑 自定义列
                if (!f.onLocked) {
                    mySetplainOptions.push({
                        label: f.name,
                        value: code
                    });
                    mySetcheckedListLocal.push(code);
                }
            });
            // this.$options.vuerify = vuerify;
            console.log("mySetcheckedListLocal", mySetcheckedListLocal);
            console.log("initFormData", initFormData);
            this.mySetcheckedList = mySetcheckedListLocal;
            let vm = this;
            console.log("initValidator_formRules,", formRules, formErrors, this.formPostData);
            initValidator(vm, formRules, formErrors);
            Object.assign(this, {
                initFormData,
                mySetplainOptions,
                mySetcheckedListLocal
            });
            //此处处理 往来单位维护中 常用信息和基本信息
            if (this.$route.path == '/finance/setting/financeContacts') {
                let dongtaiData = _.cloneDeep(initFormData);
                this.commonlyData = dongtaiData.filter(d => { return d.dataTab == '常用信息' });
                this.basicData = dongtaiData.filter(d => { return d.dataTab == '基本信息' });
                this.contactsAttrData = dongtaiData.filter(d => { return d.dataTab == '往来分类' });
            }

        },
        //3.获取用户自定义列
        getUserFieldDetail () {
            const { searchType } = this;
            let postData = {
                type: searchType
            };
            UserFieldDetail(postData).then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    if (data) {
                        const { fieldCode } = data;
                        if (fieldCode) {
                            let codeArr = fieldCode.split(",");
                            if (codeArr.length > 0) {
                                Object.assign(this, {
                                    mySetcheckedList: codeArr,
                                    mySetcheckedListLocal: codeArr
                                });
                            }
                        }
                    }
                    //初始化表头
                    this.initColumns();
                }
            })
                .catch(error => { });
        },
        //4.初始化 表头
        initColumns () {
            console.log("initColumns...");
            const {
                onOffDefineFields,
                onOffDefineFields2Map,
                onOffDefineFields4Map,
                customRenderCode,
                RenderCodeChange,
                fiexdColumnInTbCodes
            } = this;
            let allColumns = [];
            onOffDefineFields.forEach(item => {
                let code = item.code;
                if (item.dataType == 3 || item.dataType == 4) {
                    code = item.parentCode;
                }
                if (item.dataType == 2) {
                    onOffDefineFields2Map.set(item.id, item);
                } else if (item.dataType == 4) {
                    onOffDefineFields4Map.set(item.id, item);
                }
                let scopedSlots = null;
                let customRender = null;
                let sorter = false;
                let key = code;
                //插槽
                if (customRenderCode.includes(code)) {
                    let customRenderName = code;
                    if (RenderCodeChange[code]) {
                        customRenderName = RenderCodeChange[code];
                    }
                    scopedSlots = { customRender: customRenderName };
                } else if (item.type == '搜索选择' || item.type == '查询下拉') {
                    customRender = (text, row, index) => {
                        return row[IdFieldToNameField(code)];
                    }
                } else if (item.type == '日期') {
                    customRender = (text, row, index) => {
                        return text && text.substr(0, 10);
                    }
                }
                //是否排序
                if ("crmName" == code) {
                    sorter = true;
                    key = "crm.crm_name"
                }
                let column = {
                    title: item.name,
                    dataIndex: code,
                    sorter,
                    key,
                    align: "left",
                    width: item.columnWidth,
                    onLocked: item.onLocked
                }


                if (scopedSlots) {
                    column.scopedSlots = scopedSlots;
                }
                if (customRender) {
                    column.customRender = customRender;
                }
                //todo 后期优化
                if (fiexdColumnInTbCodes.includes(code)) {
                    allColumns.unshift(column)
                    //  column.fixed = "left";
                } else {
                    allColumns.push(column);
                }
                // mobile 字段 后面追加 拨打列
                if (this.$route.path != '/finance/setting/financeContacts') {
                    if ("mobile" == code) {
                        let column1 = {
                            title: "外呼拨打",
                            dataIndex: "callingOpration",
                            sorter: false,
                            key: "callingOpration",
                            align: "center",
                            width: 100,
                            onLocked: true,
                            scopedSlots: { customRender: "callingOpration" }
                        }
                        allColumns.push(column1);
                        let column2 = {
                            title: "是否任务",
                            dataIndex: "isTasking",
                            sorter: false,
                            key: "isTasking",
                            align: "center",
                            width: 100,
                            onLocked: true,
                            customRender: (text, row, index) => {
                                return text ? '是' : '否';
                            }
                            // scopedSlots: { customRender: "callingOpration" }
                        }
                        allColumns.push(column2);
                    }
                }
                if (this.$route.path == '/finance/setting/financeContacts') {
                    if (code == "crmName") {
                        allColumns.push({
                            dataIndex: 'isType',
                            key: 'isType',
                            title: "性质",
                            sorter: false,
                            align: "center",
                            width: 100,
                            onLocked: true,
                            customRender: (text, record, index) => {
                                if (record.isCustomer && record.isSupplier) {
                                    return '客户/供应商'
                                } else if (record.isCustomer) {
                                    return '客户'
                                } else if (record.isSupplier) {
                                    return '供应商'
                                }
                            }
                        })
                    }
                }

            });

            if (this.$route.path == '/crm/touch/list') {
                //如果是联系记录 增加 “跟进方式”列
                allColumns.some(res => {
                    if (res.dataIndex == 'type') {
                        res.customRender = (text, record, index) => {
                            return text == 1 ? '会话沟通' : text == 2 ? '外勤签到' : '';
                        }
                    }
                })
                // allColumns.push({
                //     title: '跟进方式',
                //     dataIndex: 'type',
                //     align: "left",
                //     width: 140,
                //     onLocked: true,
                //     customRender: (text, record, index) => {
                //         return text == 1 ? '会话沟通' : text == 2 ? '外勤签到' : '';
                //     }
                // })
            }



            console.log("所有allColumns", allColumns)
            Object.assign(this, {
                allColumns
            });
            this.updateColumns();
        },
        //5.更新表头
        updateColumns () {
            console.log(this.mySetcheckedList)
            const { columns, allColumns, mySetcheckedList } = this;

            console.log(this.$route.path);
            // allColumns.splice(4, 0,)

            let newColumns = allColumns.filter(
                f =>
                    mySetcheckedList.includes(f.dataIndex) || f.onLocked
            );
            console.log("updateColumns_newColumns", newColumns);

            newColumns = newColumns.filter(item => item.dataIndex != 'isSupplier' && item.dataIndex != 'isCustomer');

            newColumns.forEach((item, index) => {
                if (item.dataIndex == 'crmName') {
                    item.scopedSlots = {
                        filterDropdown: 'filterDropdown',
                        filterIcon: 'filterIcon',
                        customRender: 'crmName'
                    }
                }
                if (item.dataIndex == 'lastTouchSummary') {
                    item.scopedSlots = {
                        customRender: 'lastTouchSummary'
                    }
                }
            });
            Object.assign(this, {
                columns: newColumns
            });
        },
        //初始化 自定义的值(编辑时使用)
        initCustomize () {
            const { defineFields } = this.formPostData;
            const { onOffDefineFields, formPostData } = this;
            let defineFieldsObj = JSON.parse(defineFields);
            let defineFieldsSets = onOffDefineFields.filter(f => f.dataType == 2);
            defineFieldsSets.forEach(item => {
                const { id, code, name } = item;
                let value = defineFieldsObj[id + ""];
                if (value) {
                    this.$set(this.formPostData, code, value);
                }
            });
            console.log("初始化 自定义的值", formPostData)
        },
        //获取重组后的自定义集合（保存时使用）
        getDefineFields (defineFields, formPostData, defineFieldsSets) {
            defineFieldsSets &&
                defineFieldsSets.forEach(item => {
                    const { id, code, name } = item;
                    let val = formPostData[code];
                    if (val) {
                        defineFields[id + ""] = val;
                    }
                });
        },
        //转换自定义数据数据
        defineFieldsAddToData (records) {
            const { onOffDefineFields2Map, onOffDefineFields4Map, getNewKey } = this;
            console.log(onOffDefineFields2Map, onOffDefineFields4Map)
            records && records.forEach && records.forEach(f => {
                if (f.defineFields) {
                    let defineFields = JSON.parse(f.defineFields);
                    let newDefineFields = this._.mapKeys(defineFields, function (value, key) {
                        let newKey = getNewKey(key, onOffDefineFields2Map, onOffDefineFields4Map)
                        return newKey;
                    });
                    Object.assign(f, { ...newDefineFields });
                }
                if (f.crm_defineFields) {
                    let crm_defineFields = JSON.parse(f.crm_defineFields);
                    let newDefineFields = this._.mapKeys(crm_defineFields, function (value, key) {
                        let newKey = getNewKey(key, onOffDefineFields2Map, onOffDefineFields4Map)
                        return newKey;
                    });
                    Object.assign(f, { ...newDefineFields });
                }
                if (f.linkMan_defineFields) {
                    let linkMan_defineFields = JSON.parse(f.linkMan_defineFields);
                    let newDefineFields = this._.mapKeys(linkMan_defineFields, function (value, key) {
                        let newKey = getNewKey(key, onOffDefineFields2Map, onOffDefineFields4Map)
                        return newKey;
                    });
                    Object.assign(f, { ...newDefineFields });
                }
            });
        },
        getNewKey (key, onOffDefineFields2Map, onOffDefineFields4Map) {
            let defineSet = onOffDefineFields2Map.get(parseInt(key));
            if (defineSet) {
                return defineSet.code;
            } else {
                let defineParentSet = onOffDefineFields4Map.get(parseInt(key));
                if (defineParentSet) {
                    return defineParentSet.code;
                }
            }
        },
        //匹配并赋值
        findVal (defineFields, f) {
            const { onOffDefineFields2Map, onOffDefineFields4Map } = this;
            defineFields.forEach(d => {
                let defineSet = onOffDefineFields2Map.get(d.id);
                if (defineSet) {
                    f[defineSet.code] = d.val;
                } else {
                    let defineParentSet = onOffDefineFields4Map.get(d.id);
                    if (defineParentSet) {
                        f[defineParentSet.code] = d.val;
                    }
                }
            });
        },
        //切换 是否展开 更多搜索条件
        showFunction () {
            this.show = !this.show;
        },
        showModal (editItem) {
            console.log("editItem", editItem);
            this.editItem = { ...editItem };
            this.ModalVisible = true;
        },
        hideModal () {
            const { formPostData, formErrors } = this;
            clearValue(formPostData);
            clearKeys(formErrors);
            this.ModalVisible = false;
            this.isFromShow = false;

            console.log("hideModal_formErrors->", formErrors, formPostData)

        },
        //tabale check触发
        selection (keys, rows) {
            this.selectedKeys = keys;
            this.selectedRows = rows;
        },
        //改变分页大小
        changePageSize (e) {
            const value = e.target.value;
            let size = Number.parseInt(value);
            if (!size) {
                size = 20;
            }
            if (size > 500) {
                size = 500;
            }
            const { pagination } = this;

            console.log(e, value);
            Object.assign(this.postData.page, {
                current: 1,
                size
            });
            Object.assign(this.pagination, {
                current: 1,
                pageSize: size
            });
            console.log("改变分页大小_pagelist")
            if (this.isHistoryFlag) {
                this.PageList('history');
            } else {
                this.PageList();
            }
        },

        onTableChange (pagination, filters, sorter) {
            Object.assign(this.postData.page, {
                current: pagination.current,
                size: pagination.pageSize
            });
            Object.assign(this.pagination, {
                current: pagination.current,
                pageSize: pagination.pageSize
            });
            Object.assign(this.postData, {
                sortField: sorter.columnKey,
                sortOrder: sorter.order
            });
            console.log("排序字段：", sorter)
            if (this.isHistoryFlag) {
                this.PageList('history');
            } else {
                this.PageList();
            }
        },
        //初始化 动态条件
        initConditions () {
            const { userSearchSelectItem, conditions } = this;
            const { searchVal } = userSearchSelectItem;
            this.postData = deepCopy(this.basePostData, true);
            if (!searchVal) return false;
            let searchValObj = JSON.parse(searchVal);
            console.log("searchValObj", searchValObj)

            conditions.forEach((f, index) => {
                delete f.value;
                delete f.rangDateVal;
                let code = f.code;
                if (f.dataType == 3 || f.dataType == 4) {
                    code = f.parentCode;
                }
                let value = searchValObj[code];
                // console.log("code",code,"value",value)
                if (value) {
                    if (f.type == "时间" || f.type == "日期") {
                        let arr = [...value];
                        let dateType = arr[0];
                        /***** 重新计算当前时间 *****/
                        let beginDate, endDate;
                        switch (dateType) {
                            case "今日":
                                beginDate = getDate.getToday().starttime;
                                endDate = getDate.getToday().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "昨日":
                                beginDate = getDate.getYesterday().starttime;
                                endDate = getDate.getYesterday().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "本周":
                                beginDate = getDate.getCurrWeekDays().starttime;
                                endDate = getDate.getCurrWeekDays().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "上周":
                                beginDate = getDate.getLastWeekDays().starttime;
                                endDate = getDate.getLastWeekDays().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "本月":
                                beginDate = getDate.getCurrMonthDays().starttime;
                                endDate = getDate.getCurrMonthDays().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "上月":
                                beginDate = getDate.getLastMonthDays().starttime;
                                endDate = getDate.getLastMonthDays().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "本季度":
                                beginDate = getDate.getCurrQuarter().starttime;
                                endDate = getDate.getCurrQuarter().endtime;
                                arr[1] = [beginDate, endDate]; break;
                            case "上季度":
                                beginDate = getDate.getLastQuarter().starttime;
                                endDate = getDate.getLastQuarter().endtime;
                                arr[1] = [beginDate, endDate]; break;
                        }
                        console.log("初始化 动态条件:arr__", arr);
                        f.rangDateVal = arr;
                    }
                    // else if (f.type == "搜索选择") {
                    //     f.value = parseInt(value);
                    // }
                    else {
                        f.value = value;
                    }
                }
                this.$set(this.conditions, index, f);
            });
        },
        //重置 动态条件
        resetConditions () {
            Object.assign(this.postData, deepCopy(this.basePostData, true));
            this.pagination.current = 1;
            const { conditions } = this;
            conditions.forEach &&
                conditions.forEach((f, index) => {
                    delete f.value;
                    delete f.rangDateVal;
                    this.$set(this.conditions, index, f);
                });
            //重置 常用查询条件选项
            Object.assign(this, {
                userSearchSelect: "",
                userSearchSelectItem: {},
                isCollected: false
            })
            console.log("this.conditions", this.conditions);
        },
        // GetCustomizeList
        //重置
        reset () {
            //重置 动态条件
            this.resetConditions();

            console.log("重置_pagelist")
            this.PageList();
        },

        showMySet () {
            this.mySetVisible = true;
        },
        onMySetClose () {
            this.mySetVisible = false;
            this.mySetcheckedListLocal = this.mySetcheckedList;
            console.log(
                "onMySetClose_mySetcheckedListLocal",
                this.mySetcheckedListLocal
            );
        },
        saveMyShow () {
            this.mySetVisible = false;
            this.mySetcheckedList = this.mySetcheckedListLocal;
            console.log("saveMyShow_mySetcheckedList", this.mySetcheckedList);
            this.updateColumns();
            this.UserFieldSave();
            //更新 表头
        },
        onMySetChange (checkedValue) {
            console.log("checkedValue", checkedValue);
            // this.mySetcheckedListLocal = checkedValue;
        },

        //保存 用户自定义列
        UserFieldSave () {
            const { searchType, mySetcheckedListLocal } = this;
            let postData = {
                type: searchType,
                fieldCode: mySetcheckedListLocal.join(",")
            };
            UserFieldSave(postData)
                .then(response => {
                    if (response.code === 200) {
                        this.$message.success("保存成功");
                    }
                })
                .catch(error => { });
        },
        hideOfficeModal () {
            this.$refs["user-modal"].hide();
        },
        //获取用户常用查询条件
        UserSearchDetail () {
            const { searchType } = this;
            let postData = {
                searchType: searchType
            };
            UserSearchDetail(postData)
                .then(response => {
                    if (response.code === 200) {
                        const { data } = response;
                        this.userSearchList = data;

                        //重新计算是否展示方案下拉按钮
                        this.$nextTick(() => {
                            this.showDownCheck();
                        })
                    }
                })
                .catch(error => { });
        },
        //保存 用户常用查询
        UserSearchSave () {

            const { UsRules, UsErrors, userSearchEditItem, searchType, onOffDefineFields, conditions } = this;
            const { id, searchName } = userSearchEditItem;
            //全部校验一次
            checkAll(this, UsRules, userSearchEditItem, UsErrors);
            console.log("全部校验一次_userSearchEditItem", userSearchEditItem, "UsErrors", UsErrors)
            if (Object.keys(UsErrors).length > 0) {
                this.isFromShow = false;
                this.isFromShow = true;
                return false;
            }
            // 组装查询条件对象
            let searchVal = new Object();
            conditions.forEach(f => {
                let code = f.code;
                if (f.dataType == 3 || f.dataType == 4) {
                    code = f.parentCode;
                }
                if (f.value) {
                    searchVal[code] = f.value;
                } else if (f.rangDateVal) {
                    searchVal[code] = f.rangDateVal;
                }
            });
            console.log("searchVal", searchVal)
            //gw 注释2021年8月16日14:57:51
            // if (!searchVal || Object.keys(searchVal).length == 0) {
            //     this.$nlyaToast.toast("常用查询条件不能为空", {
            //         title: `错误`,
            //         variant: "danger",
            //         solid: true
            //     });
            //     return false;
            // }
            let postData = {
                id,
                searchName, //视图名称
                searchVal: JSON.stringify(searchVal),  //视图内容
                searchType  //视图类型
            };
            UserSearchSave(postData).then(response => {
                if (response.code === 200) {
                    this.$message.success("保存成功");
                    this.hideUsModal();
                    this.UserSearchDetail();
                }
            })
                .catch(error => { });
        },
        //删除 用户常用查询条件 事件
        onUserSearchDelete (item) {
            let { userSearchList } = this;
            let _this = this;
            this.$confirm({
                title: '提示',
                content: '您确定要删除该记录吗？',
                onOk () {
                    UserSearchDelete({ id: item.key }).then(response => {
                        if (response.code === 200) {
                            _this.$message.success("删除成功");
                            //删除
                            userSearchList = userSearchList.filter(f => f.id != item.key);
                            Object.assign(_this, {
                                userSearchList
                            })
                            //处理 选中的 被删除
                            if (_this.userSearchSelect == item.key) {
                                //特殊处理
                                _this.reset();
                                _this.hideUsModal();
                            }
                            _this.planActive = 0;
                            //重新计算是否展示方案下拉按钮
                            _this.$nextTick(() => {
                                _this.showDownCheck();
                            })
                        }
                    })
                },
                onCancel () {

                },
            });
        },
        //选择 用户常用查询条件 事件
        onUserSearchChange (value) {
            this.planActive = value;
            const { userSearchList, userSearchEditItem } = this;
            //如果选中了值
            if (value) {
                let intValue = parseInt(value);
                const find = userSearchList.find(f => f.id == intValue);
                if (find) {
                    Object.assign(this, {
                        userSearchSelectItem: find
                    });
                    Object.assign(this.userSearchEditItem, { ...find });
                    //赋值 动态查询条件
                    this.initConditions();
                    this.PageList();
                }
                this.userSearchSelect = intValue;
            } else {
                clearValue(userSearchEditItem);
                //清除 动态查询条件
                this.reset();
                this.planActive = 0;
            }

        },
        //打开 userSearch 弹窗
        showUsModal (type) {
            //type:2 另存 type：1 修改
            const { userSearchSelectItem, userSearchEditItem } = this;
            console.log("showUsModal_")
            Object.assign(userSearchEditItem, {
                id: type == 1 ? userSearchSelectItem.id : null,
                searchName: type == 1 ? userSearchSelectItem.searchName : null,
            })
            this.UsVisible = true;
        },
        //关闭 userSearch 弹窗
        hideUsModal () {
            const { UsErrors, userSearchEditItem } = this;
            this.UsVisible = false;
            clearValue(userSearchEditItem);
            clearValue(UsErrors);

        },
        //检查
        checkSingleSelectKey (isMultiple) {
            const { selectedKeys } = this;
            //检查选择的key
            if (selectedKeys.length == 0) {
                this.$message.warn("没有选择记录");
                return false;
            } else if (!isMultiple && selectedKeys.length > 1) {
                this.$message.warn("只能选择一条记录");
                return false;
            }
            return true;
        },
        /**
         * gw 处理方案过多溢出 2021年8月28日09:11:29
         */
        showDownCheck () {
            //方案 和 外层box 宽度比较
            if (document.getElementsByClassName('item-small').length == 0) {
                //处理和其他页面同时打开,获取不到该bom报错的处理
                return;
            }
            let planWidth = document.getElementsByClassName('item-small')[0].clientWidth;
            let planList = document.getElementsByClassName('item-plan');
            let planListWidthTotal = null;
            planList.forEach(item => {
                // console.log(item.clientWidth)
                planListWidthTotal = planListWidthTotal + item.clientWidth;
            });
            planListWidthTotal = planListWidthTotal + planList.length * 5;

            // console.log('方案总长度：', planListWidthTotal, ',当前显示方案dom的宽度：', planWidth)
            if (planListWidthTotal > planWidth) {
                this.showDownPlan = true;
                this.iconDirection = true;
            } else {
                this.showDownPlan = false;
                this.iconDirection = false;
            }
        },
        showDownPlanFun () {
            let planBox = this.$refs.planLi;
            //显示更多的方案
            this.$nextTick(() => {
                if (planBox.clientHeight == 40) {
                    this.iconDirection = false;
                    planBox.style.height = 'auto';
                } else {
                    this.iconDirection = true;
                    planBox.style.height = '40px'
                }
            })
        },
        getDynamic (source) {
            //获取动态字段
            let postData = {
                source: source
            }
            DefineFieldList(postData).then(response => {
                let backData = response.data;
                if (this.addActiveKey == 2) {
                    this.peopleData = backData.filter(res => { return res.onOff && res.onEdit });
                } else if (this.addActiveKey == 3) {
                    this.financeData = backData.filter(res => { return res.onOff && res.onEdit });
                }
            })
        },
    },
    watch: {
        // "customerId":function(n,o){
        //   const {basePostData} = this;
        //   basePostData.customerIds = n;
        //   this.reset();
        //   this.selectedKeys = [];
        // },
        "formPostData.id" (val) {
            console.log(val);
            checkNew(val);
        }
    }
};
